package leaf.cloud.system.api.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import leaf.cloud.common.redis.service.RedisService;
import leaf.cloud.common.redis.service.RedisServiceZero;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 微信Token工具类
 *
 * @author yzh
 * @since 2022/7/1 15:15
 */
@Component
@Slf4j
public class QyWechatTokenUtil {

    /**
     * 企业ID
     */
    //private static final String corpID = "wwcf2cfe00b062506e";
    private static final String tokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
    private static final String ticketURL = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=";
    private static RedisServiceZero redisUtils;

    @Autowired
    public QyWechatTokenUtil(RedisServiceZero redisServiceZero) {
        QyWechatTokenUtil.redisUtils = redisService;
    }

    public static String getDefaultAccess(WechatSecretEnum secretEnum) {
        return getAccessToken(CommonConstants.QyWechatCorp, secretEnum);
    }

    public static String getEnterpriseToken(String enterpriseId, WechatSecretEnum secret) {
        OrgEnterpriseWx enterpriseWx = enterpriseWxService.getByEnterpriseId(enterpriseId);
        if (null == enterpriseWx) {
            throw new IllegalStateException("Unexpected " + "企业未配置微信相关秘钥");
        }
        switch (secret) {
            //case ACCESS_TOKEN: return getAccessToken(agentEnum, CommonConstants.QyWechatCorp, WechatSecretEnum.INFORM.getSecret());
            case MEMBER:
                return getAccessToken(enterpriseWx.getCorpId(), WechatSecretEnum.MEMBER);
            case INFORM:
                return getAccessToken(enterpriseWx.getCorpId(), WechatSecretEnum.INFORM);
            default:
                throw new IllegalStateException("Unexpected value: " + secret);
        }
    }

    private static String getAccessToken(String corpId, WechatSecretEnum secret) {
        String accessToken = redisUtils.get(secret.getName() + corpId, String.class);
        System.out.println(secret.getName() + corpId + ":::" + accessToken);
        if (StringUtils.isEmpty(accessToken)) {
            WechatResult result = JSONObject.parseObject(HttpUtil.get(String.format(tokenURL, corpId, secret)), WechatResult.class);
            if (0 == result.getErrCode()) {
                accessToken = result.getAccessToken();
                redisUtils.setex(secret.getName() + corpId, accessToken, result.getExpiresIn() - 500, TimeUnit.SECONDS);
            } else {
                log.error(String.valueOf(result));
            }
        }
        return accessToken;
    }

}
